package git.bankview.wl.common;

import java.util.*;
import java.text.*;
import java.sql.*;

import laya.semi.process.*;

import git.bankview.sl.db.*;

import org.apache.log4j.Logger;

public abstract class SqlQueryActivityBase
	implements IGenericClassActivity
{
	private static Logger log = Logger.getLogger(SqlQueryActivityBase.class);
   
	public void execute(IProcessContext oCtx)
		throws Exception
	{
		StringBuffer oSql = buildSqlBuffer(oCtx);
		
		Integer[] vSortIndexes = (Integer[])oCtx.getField("sortIndexes");
		if (null != vSortIndexes)
		{
			for (int i = 0; i < vSortIndexes.length; ++i)
			{
				if (0 == i)
					oSql.append(" ORDER BY ");
				else
					oSql.append(", ");
				
				if (0 < vSortIndexes[i].intValue())
					oSql.append(vSortIndexes[i]);
				else
					oSql.append(-vSortIndexes[i].intValue()).append(" DESC");
			}
		}
		
		Vector v = new Vector();
		Connection oConn = DBConnectionFactory.getCoreConnection();
		
		Integer oRowsPerPage = (Integer)oCtx.getField("rowsPerPage");
		int nRowsPerPage = oRowsPerPage.intValue();
		Integer oPageIndex = (Integer)oCtx.getField("pageIndex");
		int nPageIndex = oPageIndex.intValue();
		int nTotalRows = -1;

		try
		{
			IObjectFilter filter = createNewFilter(oCtx);
			if (null == filter)
				nTotalRows = DBUtil.simpleSQLExecute(v, oSql.toString(), nRowsPerPage * nPageIndex, nRowsPerPage, oConn);
			else
				nTotalRows = DBUtil.simpleSQLExecute(v, oSql.toString(), nRowsPerPage * nPageIndex, nRowsPerPage, oConn, filter);
		}
		finally
		{
			oConn.close();
		}
		
		//oCtx.setField("searchResult", v);
		oCtx.setField(oCtx.getActivityParameter(), v);
		oCtx.setField("totalRows", new Integer(nTotalRows));
		if (0 < nRowsPerPage)
		{
			oCtx.setField("totalPages", new Integer((nTotalRows - 1) / nRowsPerPage + 1));
		}
	}
	
	public IObjectFilter createNewFilter(IProcessContext oCtx)
	{
		// default no filter
		return null;
	}

	protected abstract StringBuffer buildSqlBuffer(IProcessContext oCtx)
		throws Exception;
}
